package top.fkxuexi.blogapi.core.config.shiro;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * 当配置了多个Realm时，我们通常使用的认证器是shiro自带的org.apache.shiro.authc.pam.ModularRealmAuthenticator，
 * 其中决定使用的Realm的是doAuthenticate()方法
 *
 * 自定义Authenticator
 * 对应的Realm 的类名中应该要包含 type对应的字符串
 */
public class CustomerModularRealmAuth extends ModularRealmAuthenticator{


    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

        ShiroToken token = (ShiroToken) authenticationToken;
        String type = token.getUserType();
        Collection<Realm> realms = getRealms();
        List<Realm> typeRealms = new ArrayList<>();

        for (Realm realm : realms) {
            //对应的Realm 的类名中应该要包含 type对应的字符串 且注意这个地方 contains 是区分大小写的

            String name = realm.getName();

            if (realm.getName().contains(type)){
                typeRealms.add(realm);
            }
        }
        if (typeRealms.size() == 1){
            return doSingleRealmAuthentication(typeRealms.get(0), token);
        }
        else{
            return doMultiRealmAuthentication(typeRealms, token);
        }
    }

}
